<template>
  <div style="height: 100%">
    <Row>
      <Row class="funcContainer">
        <Col span="8">
          <Input
            search
            clearable
            enter-button
            size="large"
            placeholder="搜索用户"
            v-model="name"
            @on-search="queryUser"
            @on-clear="clearSearch"
          >
          </Input>
        </Col>
        <Col span="4" offset="12">
          <div class="btnContainer">
            <Button class="btn" size="large" @click="deleteUsers"
              ><Icon type="ios-trash-outline" />&nbsp;删除</Button
            >
            <Button class="btn" size="large" @click="registUser"
              ><Icon type="md-add" />&nbsp;新建</Button
            >
          </div>
        </Col>
      </Row>
      <Col span="24" class="tableContainer">
        <Table
          :columns="columns"
          :data="userList"
          border
          @on-selection-change="selectionChange"
        >
          <template slot-scope="{ row }" slot="action">
            <Button
              type="primary"
              style="margin-right: 10px"
              size="small"
              @click="viewUser(row)"
              >查看</Button
            >
            <Button size="small" type="error" @click="deleteUser(row)"
              >删除</Button
            >
          </template>
        </Table>
        <div class="pageContainer">
          <Page
            :total="userListTotal"
            show-elevator
            show-total
            @on-change="pageParams"
            :disabled="isPageDisabled"
          ></Page>
        </div>
      </Col>
    </Row>
    <Modal v-model="isModalShow" :title="modalTitle" @on-ok="okClick">
      <div id="modalContainer" v-if="isModalShow">
        <Row>
          <Col span="24" style="margin-bottom: 25px" v-show="!isRegist"
            ><Button type="primary" style="float: right" @click="edit"
              >编辑</Button
            ></Col
          >
          <Col span="24">
            <Form
              ref="formValidate"
              :label-width="100"
              :model="userForm"
              :disabled="!isEdit"
            >
              <FormItem label="用户名" prop="username" :error="nameErr">
                <Input
                  v-model="userForm.username"
                  placeholder="请输入用户名"
                  v-if="isRegist"
                ></Input>
                <Input
                  v-model="userForm.username"
                  placeholder="请输入用户名"
                  disabled
                  v-else
                ></Input>
              </FormItem>
              <FormItem
                label="密码"
                prop="password"
                v-show="isRegist"
                :error="passwordErr1"
              >
                <Input
                  type="password"
                  v-model="userForm.password"
                  placeholder="请输入密码"
                ></Input>
              </FormItem>
              <FormItem
                label="再次输入密码"
                prop="password2"
                :error="passwordErr2"
                v-show="isRegist"
              >
                <Input
                  type="password"
                  v-model="userForm.password2"
                  placeholder="请再次输入密码"
                ></Input>
              </FormItem>
              <FormItem label="角色" prop="role" v-if="isRegist">
                <Select v-model="userForm.role">
                  <Option
                    v-for="(role, index) in roleList"
                    :key="index"
                    :value="role.id"
                    >{{ role.roleName }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem label="角色" prop="role" v-else>
                <Select v-model="userForm.role" :placeholder="userForm.role">
                  <Option
                    v-for="(role, index) in roleList"
                    :key="index"
                    :value="role.id"
                    >{{ role.roleName }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem label="姓名" prop="xingming" :error="xingmingErr">
                <Input
                  v-model="userForm.xingming"
                  placeholder="请输入姓名"
                ></Input>
              </FormItem>
              <FormItem label="手机" prop="phone">
                <Input
                  type="tel"
                  v-model="userForm.phone"
                  placeholder="请输入手机号"
                ></Input>
              </FormItem>
              <FormItem label="邮箱" prop="mail" :error="emailErr">
                <Input
                  type="email"
                  v-model="userForm.mail"
                  placeholder="请输入邮箱"
                ></Input>
              </FormItem>
              <FormItem label="描述" prop="desc">
                <Input
                  type="textarea"
                  :rows="3"
                  v-model="userForm.desc"
                  placeholder="请输入用户描述"
                ></Input>
              </FormItem>
            </Form>
          </Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>
<style scoped>
.funcContainer {
  width: 100%;
}
.btnContainer {
  display: flex;
  justify-content: space-around;
}
.btn {
  margin: 0 1rem;
  background: rgb(0, 63, 84) !important;
  color: rgb(255, 255, 255, 0.8);
}
.tableContainer {
  margin-top: 30px;
}
.pageContainer {
  text-align: right;
  margin-top: 10rem;
}
#modalContainer {
  padding: 30px;
}
</style>
<script>
import config from "../config";
import qs from "qs";
export default {
  name: "UserManage",
  data() {
    return {
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "用户名",
          key: "username",
        },
        {
          title: "角色",
          key: "role",
        },
        {
          title: "姓名",
          key: "xingming",
        },
        {
          title: "操作",
          slot: "action",
          width: 160,
          align: "center",
        },
      ],
      page: "",
      size: 10,
      userList: [],
      userListTotal: 0,
      name: "",
      isPageDisabled: false,
      selections: [],
      registInfo: {},
      isModalShow: false,
      modalTitle: "",
      roleList: [],
      userForm: {
        username: "",
        password: "",
        password2: "",
        role: "",
        xingming: "",
        phone: "",
        mail: "",
        desc: "",
      },
      passwordErr1: "",
      passwordErr2: "",
      nameErr: "",
      xingmingErr: "",
      emailErr: "",
      isRegist: true,
      isEdit: false,
      admintoken: "",
    };
  },
  methods: {
    queryUserList() {
      this.axios
        .get("/user", {
          params: {
            page: this.page,
            size: this.size,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            let index = -1;
            for (let i = 0; i < res.data.data.length; i++) {
              if (res.data.data[i].username == "fgmi_mnr") {
                index = i;
                break;
              }
            }
            if (index != -1) {
              res.data.data.splice(index, 1);
              this.userList = res.data.data;
              this.userListTotal = res.data.total - 1;
            } else {
              this.userList = res.data.data;
              this.userListTotal = res.data.total;
            }
          } else {
            this.$Message.info("没有用户");
          }
        });
    },
    queryRoleList() {
      this.axios.get("/role").then((res) => {
        if (res.data.code === 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].roleName == "default") {
              res.data.data.splice(i, 1);
              i--;
            } else if (res.data.data[i].roleName == "admin") {
              res.data.data.splice(i, 1);
              i--;
            }
          }
          this.roleList = res.data.data;
        } else {
          this.$Message.info("当前没有角色！");
        }
      });
    },
    queryUser() {
      this.axios.get("/user/" + this.name).then((res) => {
        if (res.data.code === 200) {
          this.userList = [res.data.data];
        } else {
          this.$Message.info("查询不到该用户！");
        }
      });
      this.isPageDisabled = true;
    },
    clearSearch() {
      this.queryUserList();
      this.isPageDisabled = false;
    },
    pageParams(page) {
      this.page = page;
      this.queryUserList();
    },
    viewUser(row) {
      this.axios.get("/user/" + row.username).then((res) => {
        if (res.data.code === 200) {
          this.userForm.username = res.data.data.username;
          this.userForm.role = res.data.data.role;
          this.userForm.xingming = res.data.data.xingming;
          this.userForm.phone = res.data.data.phone;
          this.userForm.mail = res.data.data.mail;
          this.userForm.desc = res.data.data.desc;
          this.isModalShow = true;
          this.isRegist = false;
          this.isEdit = false;
          this.modalTitle = "查看用户";
        } else {
          this.$Message.info("用户信息错误！");
        }
      });
    },
    deleteUser(row) {
      this.axios
        .delete("/user", {
          data: {
            usernames: [row.username],
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.deletePortalUser(row.username);
            if (row.username == sessionStorage.name) {
              sessionStorage.removeItem("name");
              sessionStorage.removeItem("token");
              sessionStorage.removeItem("selfInfo");
              location.reload("/login");
            } else {
              this.queryUserList();
            }
          } else {
            this.$Message.info("无法删除！");
          }
        });
    },
    selectionChange(selections) {
      this.selections = selections.map((selection) => {
        return selection.username;
      });
    },
    deleteUsers() {
      this.axios
        .delete("/user", {
          data: {
            usernames: this.selections,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            for (const selection of this.selections) {
              this.deletePortalUser(selection);
            }
            if (this.selections.indexOf(sessionStorage.name) == -1) {
              this.queryUserList();
            } else {
              sessionStorage.removeItem("name");
              sessionStorage.removeItem("token");
              sessionStorage.removeItem("selfInfo");
              location.reload("/login");
            }
          } else {
            this.$Message.info("删除出错！");
          }
        });
    },
    registUser() {
      this.userForm.username = "";
      this.userForm.password = "";
      this.userForm.password2 = "";
      this.userForm.role = "";
      this.userForm.xingming = "";
      this.userForm.phone = "";
      this.userForm.mail = "";
      this.userForm.desc = "";

      this.modalTitle = "注册用户";
      this.isModalShow = true;
      this.isRegist = true;
      this.isEdit = true;
      let passReg = /^(?=.*?[0-9])(?=.*?[a-z]).{8,20}$/;
      this.$watch("userForm.password", (newVal) => {
        if (passReg.test(newVal)) {
          this.passwordErr1 = "";
        } else {
          this.passwordErr1 = "密码必须包含字母、数字，且长度大于8位！！";
        }
      });
      this.$watch("userForm.password2", (newVal) => {
        if (newVal === this.userForm.password) {
          this.passwordErr2 = "";
        } else {
          this.passwordErr2 = "两次密码输入不一致，请重新输入";
        }
      });
      this.$watch("userForm.username", (newVal) => {
        if (
          newVal.includes(",") ||
          newVal.includes("，") ||
          newVal.length < 6
        ) {
          this.nameErr = "用户名不能包含特殊字符且必须大于6位！！";
        } else {
          this.nameErr = "";
        }
      });
      this.$watch("userForm.xingming", (newVal) => {
        if (newVal.includes(",") || newVal.includes("，")) {
          this.xingmingErr = "姓名不能包含特殊字符！！";
        } else {
          this.xingmingErr = "";
        }
      });
      let emailReg = /^\w+@[a-z0-9]+\.[a-z]+$/i;
      this.$watch("userForm.mail", (newVal) => {
        if (!emailReg.exec(newVal)) {
          this.emailErr = "邮箱不合法";
        } else {
          this.emailErr = "";
        }
      });
    },
    edit() {
      this.isEdit = true;
      this.modalTitle = "编辑用户";
      this.oldUserForm = this.userForm;
    },
    // 这玩意儿没用，token在login的时候拿到放sessionStorage里了
    // async getToken() {
    //   let tokenInfo = await this.axios.get("/portal/admintoken");
    //   if (tokenInfo.data.code === 200) {
    //     this.admintoken = tokenInfo.data.data;
    //   }
    // },
    createPortalUser() {
      return new Promise((resolve, reject) => {
        this.axios
          .post(
            config.portalConfig.portalAdminPreUrl + "security/users/createUser",
            qs.stringify({
              // token: this.admintoken,
              token: sessionStorage.getItem("portalToken"),
              username: this.userForm.username,
              password: this.userForm.password,
              firstname: this.userForm.xingming,
              lastname: this.userForm.xingming,
              role: "org_publisher",
              userLicenseTypeId: "creatorUT",
              email: this.userForm.mail,
              provider: "arcgis",
              f: "json",
            })
          )
          .then(
            (res) => {
              resolve(res);
            },
            (err) => {
              reject(err);
            }
          );
      });
    },
    deletePortalUser(username) {
      return new Promise((resolve, reject) => {
        this.$.post(
          config.portalConfig.portalRestPreUrl +
            `community/users/${username}/delete`,
          {
            token: this.admintoken,
            f: "json",
          }
        )
          .done((res) => {
            resolve(res);
          })
          .fail((err) => {
            reject(err);
          });
      });
    },
    // 注册逻辑分两步，注册平台用户，注册portal用户
    okClick() {
      if (this.isRegist) {
        if (
          this.nameErr ||
          this.passwordErr1 ||
          this.passwordErr2 ||
          this.xingmingErr ||
          this.emailErr
        ) {
          this.$Message.error("输入有误，请重新输入！");
        } else {
          if (this.admintoken) {
            this.axios
              .post("/user", {
                username: this.userForm.username,
                password: this.userForm.password,
                role: this.userForm.role,
                xingming: this.userForm.xingming,
                phone: this.userForm.phone,
                mail: this.userForm.mail,
                desc: this.userForm.desc,
              })
              .then(async (res) => {
                if (res.data.code == 200) {
                  try {
                    // 这一步可能会因为有网络代理，导致被portal拦截从而报错失败，
                    // 若失败则也因删除上一步数据库中的此用户
                    let portalUserResult = await this.createPortalUser();

                    if (portalUserResult.data.status === "success") {
                      this.$Message.info("注册成功！");
                      this.queryUserList();
                    } else {
                      let result = await this.axios.delete("/user", {
                        data: {
                          usernames: [this.userForm.username],
                        },
                      });
                      this.$Message.info("注册失败！");
                    }
                  } catch (error) {
                    let result = await this.axios.delete("/user", {
                      data: {
                        usernames: [this.userForm.username],
                      },
                    });
                    this.$Message.info("注册失败！");
                  }
                } else {
                  this.$Message.info("注册失败！");
                }
              });
          } else {
            this.$Message.info("注册失败！");
          }
        }
      } else if (this.isEdit) {
        if (
          this.nameErr ||
          this.passwordErr1 ||
          this.passwordErr2 ||
          this.xingmingErr ||
          this.emailErr
        ) {
          this.$Message.error("输入有误，请重新输入！");
        } else {
          let tempRole = this.userForm.role;
          this.roleList.forEach((item1) => {
            if (item1.roleName == this.userForm.role) {
              tempRole = item1.id;
            }
          });
          this.axios
            .put("/user/" + this.userForm.username, {
              role: tempRole,
              xingming: this.userForm.xingming,
              phone: this.userForm.phone,
              mail: this.userForm.mail,
              desc: this.userForm.desc,
            })
            .then((res) => {
              if (res.data.code === 200) {
                this.$Message.info("修改成功！");
                this.isModalShow = false;
                this.queryUserList();
              } else {
                this.$Message.info("修改失败！");
              }
            });
        }
      } else {
        return;
      }
    },
  },
  mounted() {
    this.queryUserList();
    this.queryRoleList();
    this.getToken();
  },
};
</script>
